package com.ds.infra.ibatis.transaction.jdbc;

import com.ds.infra.ibatis.transaction.Transaction;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.SQLException;

@Slf4j
@RequiredArgsConstructor
public class JdbcTransaction implements Transaction {

    private final Connection connection;
    private boolean autoCommit;

    @Override
    public Connection getConnection() throws SQLException {
        return connection;
    }

    @Override
    public void commit() throws SQLException {
        if (connection != null && !connection.getAutoCommit()) {
            log.debug("Committing JDBC transaction");
            connection.commit();
        }
    }

    @Override
    public void rollback() throws SQLException {
        if (connection != null && !connection.getAutoCommit()) {
            log.debug("Rolling back JDBC transaction");
            connection.rollback();
        }
    }

    @Override
    public void close() throws SQLException {
        if (connection != null) {
            resetAutoCommit();
            log.debug("Closing JDBC connection");
            connection.close();
        }
    }

    @Override
    public boolean isActive() {
        try {
            return connection != null && !connection.isClosed();
        } catch (SQLException e) {
            return false;
        }
    }

    private void resetAutoCommit() {
        try {
            if (!connection.getAutoCommit()) {
                connection.setAutoCommit(true);
            }
        } catch (SQLException e) {
            log.warn("Error resetting auto-commit to true", e);
        }
    }
}
